# -*- coding:utf-8 -*-
# @Time  : 2020/9/21 18:49
# @Author: wangxb
import datetime
import json
import os
import time
import tkinter as tk

from dateutil.relativedelta import relativedelta
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


class ChromeClient(object):
    """
        谷歌打开网页
    """

    def __init__(self, my_webdriver_path):
        self.chrome_browser = webdriver.Chrome(executable_path=my_webdriver_path)
        self.chrome_browser.maximize_window()

    def save_cookie(self, cookie_file):
        self.chrome_browser.get("https://a.weixin.qq.com/index.html")
        WebDriverWait(self.chrome_browser, 30).until(
            EC.presence_of_element_located((By.CLASS_NAME, "Client__headerInner-3aETG")))
        # 写入cookie
        cookie = self.chrome_browser.get_cookies()
        print(cookie)
        json_cookies = json.dumps(cookie)
        with open(cookie_file, 'w') as f:
            f.write(json_cookies)
        self.chrome_browser.close()

    def load_cookies(self, cookie_file):
        """
          从本地读取cookies并刷新页面,成为已登录状态
          """
        with open(cookie_file, 'r', encoding='utf-8') as f:
            listCookies = json.loads(f.read())
        # cookie = [item["name"] + "=" + item["value"] for item in listCookies]
        # print(cookie)
        # cookie_str = '; '.join(item for item in cookie)
        # print("cookiestr:" + cookie_str)
        # print(listCookies)

        self.chrome_browser.get('https://a.weixin.qq.com/client')

        for cookie in listCookies:
            if 'expiry' in cookie:
                del cookie['expiry']
            self.chrome_browser.add_cookie(cookie)
        # self.chrome_browser.get('https://a.weixin.qq.com/client')
        self.chrome_browser.refresh()

    """
    Function:
        1、进入投放管理页面-公众号小程序广告页面
        2、停在该页面，以便后续循环创建投放计划
    """

    def work_launch_list_tab(self):
        self.chrome_browser.implicitly_wait(5)
        # time.sleep(1)
        # 进入广告投放页面
        # target = self.chrome_browser.find_element_by_link_text(u'广告投放')
        # self.chrome_browser.execute_script("arguments[0].scrollIntoView();", target)
        # target.click()

        # self.chrome_browser.implicitly_wait(3)

        # 停留在公众号列表页面，让用户选择公众号后开始执行创建操作
        while True:
            time.sleep(5)
            handles = self.chrome_browser.window_handles
            handles_len = len(handles)
            if handles_len > 1:
                print("已选择公众号，即将创建投放计划")
                time.sleep(5)
                break
            else:
                print("###########请选择公众号############")

        # 切换到某个公众号tab页
        self.chrome_browser.switch_to.window(handles[1])
        # search_window = self.chrome_browser.current_window_handle
        # self.chrome_browser.switch_to.window(self.chrome_browser.window_handles[0])
        # 等待投放管理tab标签加载出来（最多等待10s）
        WebDriverWait(self.chrome_browser, 10).until(EC.presence_of_element_located((By.ID, "ad_manage")))
        # print(element)
        # 切换到投放管理tab页
        self.chrome_browser.find_element_by_id('ad_manage').click()
        # self.chrome_browser.find_element_by_link_text(u'投放管理').click()
        WebDriverWait(self.chrome_browser, 10).until(EC.presence_of_element_located((By.LINK_TEXT, u'公众号小程序广告')))
        self.chrome_browser.find_element_by_link_text(u'公众号小程序广告').click()
        # 判断完成加载公众号小程序广告
        WebDriverWait(self.chrome_browser, 10).until(
            EC.presence_of_element_located((By.XPATH, '//div[@class="wrapper-1Xta3p_lSH"]')))

    """
    Function:
        根据传入的tab ID，切换到对应tab页
    """

    def switch_tab(self, num):
        time.sleep(1)
        # 获取该窗口的所有tab页
        handles = self.chrome_browser.window_handles
        print(handles)
        # 切换到创建投放计划表单页面
        self.chrome_browser.switch_to.window(handles[num])

    """
    Function:
        在异常处理中关闭多余的tab页面（超过3个）

    """

    def close_more_tab(self):
        time.sleep(1)
        # 获取该窗口的所有tab页
        handles = self.chrome_browser.window_handles
        # print(handles)
        if len(handles) > 2:
            # 切换到多余的页面
            self.chrome_browser.switch_to.window(handles[3])
            # 关闭当前tab页
            self.chrome_browser.close()

    """
    # Function
        1、依次创建投放广告计划-展示Banner图片
    # Params
        ad_name：创建广告的名称
        local_path：本地图片路径
    """

    def work_show_banner_advertisement(self, ad_name, local_path):
        try:
            # 点击创建投放计划
            self.chrome_browser.find_element_by_css_selector('span.content-3NEGonYPL3').click()

            time.sleep(3)

            # 切换到创建页面
            self.switch_tab(2)

            # 等待创建计划页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[@class="adui-card-title"]')))
            # time.sleep(1)

            # 第一步：输入计划名称
            input_element = self.chrome_browser.find_element_by_class_name('input-2lFnByGCRh')
            input_element.send_keys(Keys.CONTROL, 'a')
            # ad_name = "ad2"
            input_element.send_keys(ad_name)
            # time.sleep(1)

            # 选择推广目标：推广我的公众号
            self.chrome_browser.find_element_by_id('PRODUCTTYPE_WECHAT').click()
            # time.sleep(1)

            # 选择投放位置：公众平台流量
            self.chrome_browser.find_element_by_xpath("//div[text()='公众平台流量']").click()
            # time.sleep(1)

            # release_type = 1
            # 根据选择的投放位置控制投放流程。按形态投放；按广告位投放。
            # 选择按形态投放,默认选择展示Banner图片
            # self.chrome_browser.find_element_by_xpath("//span[text()='按形态投放']").click()
            # time.sleep(1)

            # 点击下一步
            self.chrome_browser.find_element_by_id("plan_next_step").click()
            # time.sleep(2)

            # 第二步：广告
            # 等待广告页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="投放时间"]')))
            # 配置投放时间
            input_elements = self.chrome_browser.find_elements_by_css_selector("input.adui-input-base")
            front_date = datetime.date.today() - relativedelta(months=-1)
            later_date = datetime.date.today() - relativedelta(months=-3)
            input_elements[0].send_keys(Keys.CONTROL, 'a')
            input_elements[0].send_keys(str(front_date))
            input_elements[1].send_keys(Keys.CONTROL, 'a')
            input_elements[1].send_keys(str(later_date))
            # 关闭日期选择器弹窗
            date_elements = self.chrome_browser.find_elements_by_css_selector("div.adui-input-right")
            date_elements[1].click()
            # self.chrome_browser.find_element_by_xpath("//span[contains(text(),'选择开始和结束日期')]").click()

            # 配置出价方式:智能优化
            # self.chrome_browser.find_element_by_xpath("//span[contains(text(),'智能优化（oCPC）')]").click()
            # 配置优化目标：关注
            self.chrome_browser.find_element_by_id("bid_objective_6").click()

            # 选择定向人群
            # 选择地域
            self.chrome_browser.find_element_by_id("area_input").click()
            time.sleep(1)
            self.chrome_browser.find_element_by_xpath('//label[text()="全选"]').click()

            # 输入预算花费
            input_elements = self.chrome_browser.find_elements_by_css_selector("input.adui-input-base")
            input_elements[3].send_keys(Keys.CONTROL, "a")
            input_elements[3].send_keys("40000000")
            time.sleep(1)
            # 输入单价
            input_elements[4].send_keys(Keys.CONTROL, "a")
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            time.sleep(1)
            input_elements[4].send_keys("0.88")
            time.sleep(1)

            # 点击下一步
            self.chrome_browser.find_element_by_id("target_next_step").click()
            time.sleep(2)

            # 第三步：创意
            # 等待广告页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="创意内容"]')))
            # 上传广告位图片
            self.chrome_browser.find_element_by_id("test_material_lib_btn").click()
            # 选择本地上传
            # local_path = "D:\\sucai\\小程序banner2.png"
            self.chrome_browser.find_element_by_class_name("webuploader-element-invisible").send_keys(local_path)
            # 等待图片上传完成
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="上传成功"]')))
            # 关闭上传图片成功弹窗
            self.chrome_browser.find_element_by_id('test_progress_confirm').click()
            time.sleep(1)
            # 选择外层素材跳转：公众号详情
            self.chrome_browser.find_element_by_xpath('//span[text()="公众号详情页"]').click()

            # 点击下一步
            self.chrome_browser.find_element_by_id("test_creative_next_step").click()
            time.sleep(2)

            # 第四步：预览提交
            # 等待协议页面加载完成
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.ID, 'test_confirmed_protocol')))
            # 同意协议
            # 获取同意协议是否已被选中，选中则不再点击
            # bool_select = self.chrome_browser.find_element_by_id("test_confirmed_protocol").is_selected()
            bool_select = self.chrome_browser.find_element_by_id("test_confirmed_protocol").get_attribute(
                "aria-checked")
            # print(type(bool_select))
            if bool_select == "true":
                pass
            else:
                # 同意协议
                self.chrome_browser.find_element_by_id("test_confirmed_protocol").click()
            # time.sleep(1)
            # 提交
            self.chrome_browser.find_element_by_id("test_submit_all").click()

            # 第五步：提交验证
            # 提交成功校验
            WebDriverWait(self.chrome_browser, 5).until(
                EC.presence_of_element_located((By.XPATH, '//p[text()="广告已提交审核"]')))
            print("#############提交成功##############")

            # 关闭当前tab页
            self.chrome_browser.close()
            return True
        except Exception as exception:
            print(exception)
            # 创建计划中，出现异常关闭当前tab页
            self.chrome_browser.close()
            return False

    """
    # Function
        1、依次创建投放广告计划-优雅横版大图
    # Params
        ad_name：创建广告的名称
        local_path：本地图片路径
    """

    def work_big_picture_advertisement(self, ad_name, local_path):
        try:
            # 点击创建投放计划
            self.chrome_browser.find_element_by_css_selector('span.content-3NEGonYPL3').click()

            time.sleep(3)

            # 切换到创建页面
            self.switch_tab(2)

            # 等待创建计划页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[@class="adui-card-title"]')))
            # time.sleep(1)

            # 第一步：输入计划名称
            input_element = self.chrome_browser.find_element_by_class_name('input-2lFnByGCRh')
            input_element.send_keys(Keys.CONTROL, 'a')
            # ad_name = "ad2"
            input_element.send_keys(ad_name)
            # time.sleep(1)

            # 选择推广目标：推广我的公众号
            self.chrome_browser.find_element_by_id('PRODUCTTYPE_WECHAT').click()
            # time.sleep(1)

            # 选择投放位置：公众平台流量
            self.chrome_browser.find_element_by_xpath("//div[text()='公众平台流量']").click()
            # time.sleep(1)

            # release_type = 1
            # 根据选择的投放位置控制投放流程。按形态投放；按广告位投放。
            # 选择按形态投放
            # self.chrome_browser.find_element_by_xpath("//span[text()='按形态投放']").click()
            # time.sleep(1)

            # 选择按形态投放
            self.chrome_browser.find_element_by_xpath("//div[text()='优雅横版大图']").click()
            # time.sleep(1)

            # 点击下一步
            self.chrome_browser.find_element_by_id("plan_next_step").click()
            # time.sleep(2)

            # 第二步：广告
            # 等待广告页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="投放时间"]')))
            # 配置投放时间
            input_elements = self.chrome_browser.find_elements_by_css_selector("input.adui-input-base")
            front_date = datetime.date.today() - relativedelta(months=-1)
            later_date = datetime.date.today() - relativedelta(months=-3)
            input_elements[0].send_keys(Keys.CONTROL, 'a')
            input_elements[0].send_keys(str(front_date))
            input_elements[1].send_keys(Keys.CONTROL, 'a')
            input_elements[1].send_keys(str(later_date))
            # 关闭日期选择器弹窗
            date_elements = self.chrome_browser.find_elements_by_css_selector("div.adui-input-right")
            date_elements[1].click()
            # self.chrome_browser.find_element_by_xpath("//span[contains(text(),'选择开始和结束日期')]").click()

            # # 配置出价方式:智能优化
            # self.chrome_browser.find_element_by_xpath("//span[contains(text(),'智能优化（oCPC）')]").click()
            # 配置优化目标：关注
            self.chrome_browser.find_element_by_id("bid_objective_6").click()

            # 选择定向人群
            # 选择地域
            self.chrome_browser.find_element_by_id("area_input").click()
            time.sleep(1)
            self.chrome_browser.find_element_by_xpath('//label[text()="全选"]').click()

            # 输入预算花费
            input_elements = self.chrome_browser.find_elements_by_css_selector("input.adui-input-base")
            input_elements[3].send_keys(Keys.CONTROL, "a")
            input_elements[3].send_keys("40000000")
            time.sleep(1)
            # 输入单价
            input_elements[4].send_keys(Keys.CONTROL, "a")
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            time.sleep(1)
            input_elements[4].send_keys("0.88")
            time.sleep(1)

            # 点击下一步
            self.chrome_browser.find_element_by_id("target_next_step").click()
            time.sleep(2)

            # 第三步：创意
            # 等待广告页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="创意内容"]')))
            # 上传广告位图片
            self.chrome_browser.find_element_by_id("test_material_lib_btn").click()
            # 选择本地上传
            # local_path = "D:\\sucai\\小程序banner2.png"
            self.chrome_browser.find_element_by_class_name("webuploader-element-invisible").send_keys(local_path)
            # 等待图片上传完成
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="上传成功"]')))
            # 关闭上传图片成功弹窗
            self.chrome_browser.find_element_by_id('test_progress_confirm').click()
            time.sleep(1)

            # 滑到底部

            # 将滚动条移动到页面的底部
            # js = "var q=document.documentElement.scrollTop=100000"
            # self.chrome_browser.execute_script(js)
            # time.sleep(1)
            # 定位标题和文案输入框元素
            cy_input_elements = self.chrome_browser.find_elements_by_css_selector(
                "input.input-3MbKvywHL2")
            # 填写图文标题
            # cy_input_elements[0].send_keys(Keys.CONTROL, "a")
            cy_input_elements[0].send_keys("更多内容点击关注")
            # 填写广告文案
            cy_input_elements[1].send_keys("精彩内容送不停")
            cy_input_elements[2].send_keys("想看更多，关注公众号")
            # cy_input_elements[3].send_keys("关注公众号")
            # time.sleep(1)

            # 选择外层素材跳转：公众号详情
            self.chrome_browser.find_element_by_xpath('//span[text()="公众号详情页"]').click()

            # 点击下一步
            self.chrome_browser.find_element_by_id("test_creative_next_step").click()
            time.sleep(2)

            # 第四步：预览提交
            # 等待协议页面加载完成
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.ID, 'test_confirmed_protocol')))
            # 同意协议
            # 获取同意协议是否已被选中，选中则不再点击
            # bool_select = self.chrome_browser.find_element_by_id("test_confirmed_protocol").is_selected()
            bool_select = self.chrome_browser.find_element_by_id("test_confirmed_protocol").get_attribute(
                "aria-checked")
            # print(type(bool_select))
            if bool_select == "true":
                pass
            else:
                # 同意协议
                self.chrome_browser.find_element_by_id("test_confirmed_protocol").click()
            # time.sleep(1)
            # 提交
            self.chrome_browser.find_element_by_id("test_submit_all").click()

            # 第五步：提交验证
            # 提交成功校验
            WebDriverWait(self.chrome_browser, 5).until(
                EC.presence_of_element_located((By.XPATH, '//p[text()="广告已提交审核"]')))
            print("#############提交成功##############")

            # 关闭当前tab页
            self.chrome_browser.close()
            return True
        except Exception as exception:
            print(exception)
            # 创建计划中，出现异常关闭当前tab页
            self.chrome_browser.close()
            return False

    """
    # Function
        1、依次创建投放广告计划-小程序banner广告
    # Params
        ad_name：创建广告的名称
        local_path：本地图片路径
    """

    def work_little_banner_advertisement(self, ad_name, local_path):
        try:
            # 点击创建投放计划
            self.chrome_browser.find_element_by_css_selector('span.content-3NEGonYPL3').click()

            time.sleep(3)

            # 切换到创建页面
            self.switch_tab(2)

            # 等待创建计划页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[@class="adui-card-title"]')))
            # time.sleep(1)

            # 第一步：输入计划名称
            input_element = self.chrome_browser.find_element_by_class_name('input-2lFnByGCRh')
            input_element.send_keys(Keys.CONTROL, 'a')
            # ad_name = "ad2"
            input_element.send_keys(ad_name)
            # time.sleep(1)

            # 选择推广目标：推广我的公众号
            self.chrome_browser.find_element_by_id('PRODUCTTYPE_WECHAT').click()
            # time.sleep(1)

            # 选择投放位置：公众平台流量
            self.chrome_browser.find_element_by_xpath("//div[text()='公众平台流量']").click()
            # time.sleep(1)

            # release_type = 1
            # 根据选择的投放位置控制投放流程。按形态投放；按广告位投放。
            # 选择按广告位投放
            self.chrome_browser.find_element_by_xpath("//span[text()='按广告位投放']").click()
            # time.sleep(1)

            # 选择小程序banner广告
            self.chrome_browser.find_element_by_xpath("//div[text()='小程序banner广告']").click()
            # time.sleep(1)

            # 点击下一步
            self.chrome_browser.find_element_by_id("plan_next_step").click()
            # time.sleep(2)

            # 第二步：广告
            # 等待广告页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="投放时间"]')))
            # 配置投放时间
            input_elements = self.chrome_browser.find_elements_by_css_selector("input.adui-input-base")
            front_date = datetime.date.today() - relativedelta(months=-1)
            later_date = datetime.date.today() - relativedelta(months=-3)
            input_elements[0].send_keys(Keys.CONTROL, 'a')
            input_elements[0].send_keys(str(front_date))
            input_elements[1].send_keys(Keys.CONTROL, 'a')
            input_elements[1].send_keys(str(later_date))
            # 关闭日期选择器弹窗
            date_elements = self.chrome_browser.find_elements_by_css_selector("div.adui-input-right")
            date_elements[1].click()
            # self.chrome_browser.find_element_by_xpath("//span[contains(text(),'选择开始和结束日期')]").click()

            # 配置出价方式:智能优化
            self.chrome_browser.find_element_by_xpath("//span[contains(text(),'智能优化（oCPC）')]").click()
            # 配置优化目标：关注
            self.chrome_browser.find_element_by_id("bid_objective_6").click()

            # 选择定向人群
            # 选择地域
            self.chrome_browser.find_element_by_id("area_input").click()
            time.sleep(1)
            self.chrome_browser.find_element_by_xpath('//label[text()="全选"]').click()

            # 输入预算花费
            input_elements = self.chrome_browser.find_elements_by_css_selector("input.adui-input-base")
            input_elements[3].send_keys(Keys.CONTROL, "a")
            input_elements[3].send_keys("40000000")
            time.sleep(1)
            # 输入单价
            input_elements[4].send_keys(Keys.CONTROL, "a")
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            time.sleep(1)
            input_elements[4].send_keys("0.88")
            time.sleep(1)

            # 点击下一步
            self.chrome_browser.find_element_by_id("target_next_step").click()
            time.sleep(2)

            # 第三步：创意
            # 等待广告页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="创意内容"]')))
            # 上传广告位图片
            self.chrome_browser.find_element_by_id("test_material_lib_btn").click()
            # 选择本地上传
            # local_path = "D:\\sucai\\小程序banner2.png"
            self.chrome_browser.find_element_by_class_name("webuploader-element-invisible").send_keys(local_path)
            # 等待图片上传完成
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="上传成功"]')))
            # 关闭上传图片成功弹窗
            self.chrome_browser.find_element_by_id('test_progress_confirm').click()
            time.sleep(1)
            # 选择外层素材跳转：公众号详情
            self.chrome_browser.find_element_by_xpath('//span[text()="公众号详情页"]').click()

            # 点击下一步
            self.chrome_browser.find_element_by_id("test_creative_next_step").click()
            time.sleep(2)

            # 第四步：预览提交
            # 等待协议页面加载完成
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.ID, 'test_confirmed_protocol')))
            # 同意协议
            # 获取同意协议是否已被选中，选中则不再点击
            # bool_select = self.chrome_browser.find_element_by_id("test_confirmed_protocol").is_selected()
            bool_select = self.chrome_browser.find_element_by_id("test_confirmed_protocol").get_attribute(
                "aria-checked")
            # print(type(bool_select))
            if bool_select == "true":
                pass
            else:
                # 同意协议
                self.chrome_browser.find_element_by_id("test_confirmed_protocol").click()
            # time.sleep(1)
            # 提交
            self.chrome_browser.find_element_by_id("test_submit_all").click()

            # 第五步：提交验证
            # 提交成功校验
            WebDriverWait(self.chrome_browser, 5).until(
                EC.presence_of_element_located((By.XPATH, '//p[text()="广告已提交审核"]')))
            print("#############提交成功##############")

            # 关闭当前tab页
            self.chrome_browser.close()
            return True
        except Exception as exception:
            print(exception)
            # 创建计划中，出现异常关闭当前tab页
            self.chrome_browser.close()
            return False

    """
    # Function
        1、依次创建投放广告计划-公众号文章中部
    # Params
        ad_name：创建广告的名称
        local_path：本地图片路径
    """

    def work_middle_advertisement(self, ad_name, local_path):
        try:
            # 点击创建投放计划
            self.chrome_browser.find_element_by_css_selector('span.content-3NEGonYPL3').click()

            time.sleep(3)

            # 切换到创建页面
            self.switch_tab(2)

            # 等待创建计划页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[@class="adui-card-title"]')))
            # time.sleep(1)

            # 第一步：输入计划名称
            input_element = self.chrome_browser.find_element_by_class_name('input-2lFnByGCRh')
            input_element.send_keys(Keys.CONTROL, 'a')
            # ad_name = "ad2"
            input_element.send_keys(ad_name)
            # time.sleep(1)

            # 选择推广目标：推广我的公众号
            self.chrome_browser.find_element_by_id('PRODUCTTYPE_WECHAT').click()
            # time.sleep(1)

            # 选择投放位置：公众平台流量
            self.chrome_browser.find_element_by_xpath("//div[text()='公众平台流量']").click()
            # time.sleep(1)

            # release_type = 1
            # 根据选择的投放位置控制投放流程。按形态投放；按广告位投放。
            # 选择按广告位投放
            self.chrome_browser.find_element_by_xpath("//span[text()='按广告位投放']").click()
            # time.sleep(1)

            # 选择公众号文章中部
            self.chrome_browser.find_element_by_xpath("//div[text()='公众号文章中部']").click()
            # time.sleep(1)

            # 点击下一步
            self.chrome_browser.find_element_by_id("plan_next_step").click()
            # time.sleep(2)

            # 第二步：广告
            # 等待广告页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="投放时间"]')))
            # 配置投放时间
            input_elements = self.chrome_browser.find_elements_by_css_selector("input.adui-input-base")
            front_date = datetime.date.today() - relativedelta(months=-1)
            later_date = datetime.date.today() - relativedelta(months=-3)
            input_elements[0].send_keys(Keys.CONTROL, 'a')
            input_elements[0].send_keys(str(front_date))
            input_elements[1].send_keys(Keys.CONTROL, 'a')
            input_elements[1].send_keys(str(later_date))
            # 关闭日期选择器弹窗
            date_elements = self.chrome_browser.find_elements_by_css_selector("div.adui-input-right")
            date_elements[1].click()
            # self.chrome_browser.find_element_by_xpath("//span[contains(text(),'选择开始和结束日期')]").click()

            # 配置出价方式:智能优化
            self.chrome_browser.find_element_by_xpath("//span[contains(text(),'智能优化（oCPC）')]").click()
            # 配置优化目标：关注
            self.chrome_browser.find_element_by_id("bid_objective_6").click()

            # 选择定向人群
            # 选择地域
            self.chrome_browser.find_element_by_id("area_input").click()
            time.sleep(1)
            self.chrome_browser.find_element_by_xpath('//label[text()="全选"]').click()

            # 输入预算花费
            input_elements = self.chrome_browser.find_elements_by_css_selector("input.adui-input-base")
            input_elements[3].send_keys(Keys.CONTROL, "a")
            input_elements[3].send_keys("40000000")
            time.sleep(1)
            # 输入单价
            input_elements[4].send_keys(Keys.CONTROL, "a")
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            time.sleep(1)
            input_elements[4].send_keys("0.88")
            time.sleep(1)

            # 点击下一步
            self.chrome_browser.find_element_by_id("target_next_step").click()
            time.sleep(2)

            # 第三步：创意
            # 等待广告页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="创意内容"]')))
            # 上传广告位图片
            self.chrome_browser.find_element_by_id("test_material_lib_btn").click()
            # 选择本地上传
            # local_path = "D:\\sucai\\小程序banner2.png"
            self.chrome_browser.find_element_by_class_name("webuploader-element-invisible").send_keys(local_path)
            # 等待图片上传完成
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="上传成功"]')))
            # 关闭上传图片成功弹窗
            self.chrome_browser.find_element_by_id('test_progress_confirm').click()
            time.sleep(1)
            # 选择外层素材跳转：公众号详情
            self.chrome_browser.find_element_by_xpath('//span[text()="公众号详情页"]').click()

            # 点击下一步
            self.chrome_browser.find_element_by_id("test_creative_next_step").click()
            time.sleep(2)

            # 第四步：预览提交
            # 等待协议页面加载完成
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.ID, 'test_confirmed_protocol')))
            # 同意协议
            # 获取同意协议是否已被选中，选中则不再点击
            # bool_select = self.chrome_browser.find_element_by_id("test_confirmed_protocol").is_selected()
            bool_select = self.chrome_browser.find_element_by_id("test_confirmed_protocol").get_attribute(
                "aria-checked")
            # print(type(bool_select))
            if bool_select == "true":
                pass
            else:
                # 同意协议
                self.chrome_browser.find_element_by_id("test_confirmed_protocol").click()
            # time.sleep(1)
            # 提交
            self.chrome_browser.find_element_by_id("test_submit_all").click()

            # 第五步：提交验证
            # 提交成功校验
            WebDriverWait(self.chrome_browser, 5).until(
                EC.presence_of_element_located((By.XPATH, '//p[text()="广告已提交审核"]')))
            print("#############提交成功##############")

            # 关闭当前tab页
            self.chrome_browser.close()
            return True
        except Exception as exception:
            print(exception)
            # 创建计划中，出现异常关闭当前tab页
            self.chrome_browser.close()
            return False

    """
    # Function
        1、依次创建投放广告计划-公众号文章底部
    # Params
        ad_name：创建广告的名称
        local_path：本地图片路径
    """

    def work_bottom_advertisement(self, ad_name, local_path):
        try:
            # 点击创建投放计划
            self.chrome_browser.find_element_by_css_selector('span.content-3NEGonYPL3').click()

            time.sleep(3)

            # 切换到创建页面
            self.switch_tab(2)

            # 等待创建计划页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[@class="adui-card-title"]')))
            # time.sleep(1)

            # 第一步：输入计划名称
            input_element = self.chrome_browser.find_element_by_class_name('input-2lFnByGCRh')
            input_element.send_keys(Keys.CONTROL, 'a')
            # ad_name = "ad2"
            input_element.send_keys(ad_name)
            # time.sleep(1)

            # 选择推广目标：推广我的公众号
            self.chrome_browser.find_element_by_id('PRODUCTTYPE_WECHAT').click()
            # time.sleep(1)

            # 选择投放位置：公众平台流量
            self.chrome_browser.find_element_by_xpath("//div[text()='公众平台流量']").click()
            # time.sleep(1)

            # release_type = 1
            # 根据选择的投放位置控制投放流程。按形态投放；按广告位投放。
            # 选择按广告位投放
            self.chrome_browser.find_element_by_xpath("//span[text()='按广告位投放']").click()
            # time.sleep(1)

            # 选择公众号文章中部
            self.chrome_browser.find_element_by_xpath("//div[text()='公众号文章底部']").click()
            # time.sleep(1)

            # 点击下一步
            self.chrome_browser.find_element_by_id("plan_next_step").click()
            # time.sleep(2)

            # 第二步：广告
            # 等待广告页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="投放时间"]')))
            # 配置投放时间
            input_elements = self.chrome_browser.find_elements_by_css_selector("input.adui-input-base")
            front_date = datetime.date.today() - relativedelta(months=-1)
            later_date = datetime.date.today() - relativedelta(months=-3)
            input_elements[0].send_keys(Keys.CONTROL, 'a')
            input_elements[0].send_keys(str(front_date))
            input_elements[1].send_keys(Keys.CONTROL, 'a')
            input_elements[1].send_keys(str(later_date))
            # 关闭日期选择器弹窗
            date_elements = self.chrome_browser.find_elements_by_css_selector("div.adui-input-right")
            date_elements[1].click()
            # self.chrome_browser.find_element_by_xpath("//span[contains(text(),'选择开始和结束日期')]").click()

            # 配置出价方式:智能优化
            self.chrome_browser.find_element_by_xpath("//span[contains(text(),'智能优化（oCPC）')]").click()
            # 配置优化目标：关注
            self.chrome_browser.find_element_by_id("bid_objective_6").click()

            # 选择定向人群
            # 选择地域
            self.chrome_browser.find_element_by_id("area_input").click()
            time.sleep(1)
            self.chrome_browser.find_element_by_xpath('//label[text()="全选"]').click()

            # 输入预算花费
            input_elements = self.chrome_browser.find_elements_by_css_selector("input.adui-input-base")
            input_elements[3].send_keys(Keys.CONTROL, "a")
            input_elements[3].send_keys("40000000")
            time.sleep(1)
            # 输入单价
            input_elements[4].send_keys(Keys.CONTROL, "a")
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            input_elements[4].send_keys(Keys.BACKSPACE)
            time.sleep(1)
            input_elements[4].send_keys("0.88")
            time.sleep(1)

            # 点击下一步
            self.chrome_browser.find_element_by_id("target_next_step").click()
            time.sleep(2)

            # 第三步：创意
            # 等待广告页面加载完
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="创意内容"]')))
            # 上传广告位图片
            self.chrome_browser.find_element_by_id("test_material_lib_btn").click()
            # 选择本地上传
            # local_path = "D:\\sucai\\小程序banner2.png"
            self.chrome_browser.find_element_by_class_name("webuploader-element-invisible").send_keys(local_path)
            # 等待图片上传完成
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[text()="上传成功"]')))
            # 关闭上传图片成功弹窗
            self.chrome_browser.find_element_by_id('test_progress_confirm').click()
            time.sleep(1)
            # 选择外层素材跳转：公众号详情
            self.chrome_browser.find_element_by_xpath('//span[text()="公众号详情页"]').click()

            # 点击下一步
            self.chrome_browser.find_element_by_id("test_creative_next_step").click()
            time.sleep(2)

            # 第四步：预览提交
            # 等待协议页面加载完成
            WebDriverWait(self.chrome_browser, 10).until(
                EC.presence_of_element_located((By.ID, 'test_confirmed_protocol')))
            # 同意协议
            # 获取同意协议是否已被选中，选中则不再点击
            # bool_select = self.chrome_browser.find_element_by_id("test_confirmed_protocol").is_selected()
            bool_select = self.chrome_browser.find_element_by_id("test_confirmed_protocol").get_attribute(
                "aria-checked")
            # print(type(bool_select))
            if bool_select == "true":
                pass
            else:
                # 同意协议
                self.chrome_browser.find_element_by_id("test_confirmed_protocol").click()
            # time.sleep(1)
            # 提交
            self.chrome_browser.find_element_by_id("test_submit_all").click()

            # 第五步：提交验证
            # 提交成功校验
            WebDriverWait(self.chrome_browser, 5).until(
                EC.presence_of_element_located((By.XPATH, '//p[text()="广告已提交审核"]')))
            print("#############提交成功##############")

            # 关闭当前tab页
            self.chrome_browser.close()
            return True
        except Exception as exception:
            print(exception)
            # 创建计划中，出现异常关闭当前tab页
            self.chrome_browser.close()
            return False

    def close_chrome(self):
        self.chrome_browser.close()

    def quit_chrome(self):
        self.chrome_browser.quit()


'''
Function：
    获取指定目录下的图片
Return:
    picList：图片列表
'''


def traverseDocument(searchRootPath):
    picList = []
    if os.path.exists(searchRootPath):
        for root, dirs, files in os.walk(searchRootPath, topdown=False):
            for name in files:
                # print(os.path.join(root, name))
                # print(name)
                picList.append(name)
    return picList


# 项目的根路径
root_path = os.path.dirname(os.getcwd())
# root_path = os.getcwd()
# print(root_path)
sys_image_path = root_path + os.sep + 'loading.gif'
# 图片文件路径
show_banner_path = root_path + os.sep + '展示Banner图片' + os.sep
big_pic_path = root_path + os.sep + '优雅横版大图' + os.sep
bottom_path = root_path + os.sep + '公众号文章底部' + os.sep
middle_path = root_path + os.sep + '公众号文章中部' + os.sep
little_path = root_path + os.sep + '小程序banner广告' + os.sep
cookie_file = root_path + os.sep + 'my_cookie.json'
webdriver_path = root_path + os.sep + 'chromedriver.exe'

# 第1步，实例化object，建立窗口window
window = tk.Tk()
# 第2步，给窗口的可视化起名字
window.title('Wellcome Wechat AD')
# 第3步，设定窗口的大小(长 * 宽)
window.geometry('500x400')  # 这里的乘是小x

# 第4步，加载 wellcome image
canvas = tk.Canvas(window, width=400, height=135, bg='green')
image_file = tk.PhotoImage(file=sys_image_path)
image = canvas.create_image(200, 0, anchor='n', image=image_file)
canvas.pack(side='top')
tk.Label(window, text='Wellcome', font=('Arial', 16)).pack()

# 第5步，用户信息
tk.Label(window, text='请选择是否登录：', font=('Arial', 14)).place(x=10, y=170)
tk.Label(window, text='请选择投放方式:', font=('Arial', 14)).place(x=10, y=210)

# 是否需要登录
login_tag = tk.IntVar()
is_login = tk.Checkbutton(window, text='是否登录', variable=login_tag, onvalue=1, offvalue=0)
is_login.place(x=120, y=175)
is_login.pack()

# 投放位置
choice_list = tk.Listbox(window, selectmode=tk.EXTENDED, height=5)  # 将var2的值赋给Listbox
# 创建一个list并将值循环添加到Listbox控件中
list_items = ['展示Banner图片', '优雅横版大图', '小程序banner广告', '公众号文章中部', '公众号文章底部']
for item in list_items:
    choice_list.insert('end', item)  # 从最后一个位置开始加入值
choice_list.place(x=120, y=300)
choice_list.pack()


def main_process():
    # 判断是否需要登录，选中则登录
    bool_login = login_tag.get()
    # print(bool_login)
    # 是否需要登录。bool_login：0，不需要登录；bool_login：1，需要登录；
    if bool_login == 0:
        print("您选择的是无登录方式！！！")
    else:
        print("您已选择登录方式，请稍后扫码登录！！！")
    # 获取投放的广告位置
    place = choice_list.curselection()
    if len(place) < 1:
        print("请选择投放方式！！！")
    else:
        bool_place = place[0]
        print("您已选择了投放方式：%s ！！！" % list_items[bool_place])

        # 判断是否需要登录。bool_login：0，不需要登录；bool_login：1，需要登录；
        if bool_login == 1:
            # 根据传参判断是否需要重新获取用户cookies
            chrome = ChromeClient(webdriver_path)
            # 保存用户cookies
            chrome.save_cookie(cookie_file)
        else:
            print("跳过登录页面，将根据本地保存的用户cookie进行创建投放")

        chrome = ChromeClient(webdriver_path)
        # 加载用户cookies
        chrome.load_cookies(cookie_file)
        # 配置中间转换路径
        temp_path = ''
        if bool_place == 0:
            # 展示Banner图片
            temp_path = show_banner_path
        elif bool_place == 1:
            # 优雅横版大图
            temp_path = big_pic_path
        elif bool_place == 2:
            # 小程序banner广告
            temp_path = little_path
        elif bool_place == 3:
            # 公众号文章中部
            temp_path = middle_path
        elif bool_place == 4:
            # 公众号文章底部
            temp_path = bottom_path
        # 加载本地图片
        picList = traverseDocument(temp_path)
        if len(picList) < 1:
            print("请在目录 %s ：下配置图片" % temp_path)
            quit()
        else:
            print(str(picList))

        # 进入广告投放页面
        chrome.work_launch_list_tab()

        # for循环，依次创建投放计划
        for pic_name in picList:
            # 拼接本地图片路径
            pic_path = temp_path + pic_name
            try:
                print("############开始创建： %s ##############" % pic_name)
                # 切换到计划列表页面
                chrome.switch_tab(1)
                # 创建投放计划
                pic_name = pic_name.split(".")[0]
                bool_tab = False
                if bool_place == 0:
                    # 创建展示Banner图片的广告计划
                    bool_tab = chrome.work_show_banner_advertisement(pic_name, pic_path)
                elif bool_place == 1:
                    # 创建优雅横版大图的广告计划
                    bool_tab = chrome.work_big_picture_advertisement(pic_name, pic_path)
                elif bool_place == 2:
                    # 创建小程序banner广告的广告计划
                    bool_tab = chrome.work_little_banner_advertisement(pic_name, pic_path)
                elif bool_place == 3:
                    # 创建公众号文章中部的广告计划
                    bool_tab = chrome.work_middle_advertisement(pic_name, pic_path)
                elif bool_place == 4:
                    # 创建公众号文章底部的广告计划
                    bool_tab = chrome.work_bottom_advertisement(pic_name, pic_path)
                if bool_tab:
                    print("############已完成创建： %s ##############" % pic_name)
                else:
                    print("############创建： %s 失败##############" % pic_name)
            except Exception as e:
                print(e)
                chrome.close_more_tab()
                continue

        # 退出关闭浏览器
        chrome.quit_chrome()
        print("############已全部完成##############")


# 运行按钮
btn_run = tk.Button(window, text='运行', command=main_process)
btn_run.place(x=220, y=300)

# 主窗口循环显示
window.mainloop()
